package G2017_02.L03;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class TelnetServer {

	public static void main(String[] args) throws IOException {
		Selector selector = Selector.open();
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.configureBlocking(false);
		InetSocketAddress address = new InetSocketAddress(9000);
		serverSocketChannel.socket().bind(address);
		System.out.println("started at " + address);
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		while(true){
			int selectedNum = selector.select();
			System.out.println("Selected Num is :" + selectedNum);
			Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
			while(iter.hasNext()){
				SelectionKey selectionKey = iter.next();
				if( (selectionKey.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT ){
					ServerSocketChannel serverChannel = (ServerSocketChannel) selectionKey.channel();
					SocketChannel socketChannel = serverChannel.accept();
					socketChannel.configureBlocking(false);
					socketChannel.register(selector, SelectionKey.OP_READ);
					socketChannel.write(ByteBuffer.wrap("Welcome Leader.us Power Man Java Course ...\r\n".getBytes()));
				}else if( (selectionKey.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ ){
					System.out.println("received read event");
					SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
					ByteBuffer buffer = ByteBuffer.allocate(100);
					//buffer.put("\r\nFollow you:".getBytes());
					socketChannel.read(buffer);
					int writeBufferSize = socketChannel.socket().getSendBufferSize();
					System.out.println("send buffer size:" + writeBufferSize);
					buffer = ByteBuffer.allocate(writeBufferSize*50+2);
					for(int i=0;i<buffer.capacity()-2;i++){
						buffer.put( (byte)('a'+(i%25)) );
					}
					buffer.put("\r\n".getBytes());
					buffer.flip();
					int writed = socketChannel.write(buffer);
					System.out.println("writed " + writed);
					if(buffer.hasRemaining()){
						System.out.println(" not write finished ,remains " + buffer.remaining());
					}
				}
				iter.remove();
			}
		}
	}

}
